#include "sidebar.h"

Sidebar::Sidebar(QWidget *parent) : QWidget(parent)
{
    QWidget::setWindowTitle("DOCTOR");
    backgroundColor = "#E4E4E4";
    selectedColor = "#2CA7F8";
    mouseInColor = "#C4C4C4";
    rowHeight = 40;
    currentIndex = 0;
    mouseMoveIndex = -1;

    setMouseTracking(true);
    setFixedWidth(150);
}
Sidebar::~Sidebar(){

}

void Sidebar::addItem(const QString &iconPath, const QString &title)
{
    listIcons << iconPath;
    listItems << title;

    update();
}

void Sidebar::setWidth(const int &width)
{
     setFixedWidth(width);
}

void Sidebar::setBackgroundColor(const QColor &color)
{
    backgroundColor = color;
     update();
}

void Sidebar::setSelectColor(const QColor &color)
{
    selectedColor = color;
     update();
}

void Sidebar::setMouseInColor(const QColor &color)
{
    mouseInColor = color;
     update();
}

void Sidebar::setRowHeight(const int &height)
{
    rowHeight = height;
    update();
}

void Sidebar::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
        painter.setRenderHint(QPainter::Antialiasing, true);

        // Draw background color.
        painter.setPen(Qt::NoPen);
        painter.setBrush(backgroundColor);
        painter.drawRect(rect());

        // Draw Items
        int count = 0;
        for (const QString &str : listItems)
        {
            QPainterPath itemPath;
            itemPath.addRect(QRect(0, count * rowHeight, width(), rowHeight));

            if (currentIndex == count)
            {
                painter.setPen("#FFFFFF");
                painter.fillPath(itemPath, selectedColor);
            }
            else if(mouseMoveIndex == count)
            {
                painter.setPen("#FFFFFF");
                painter.fillPath(itemPath, mouseInColor);
            }
            else
            {
                painter.setPen("#202020");
                painter.fillPath(itemPath, backgroundColor);
            }

            //painter.drawText(QRect(40, count * rowHeight, width()-40, rowHeight), Qt::AlignVCenter | Qt::AlignHCenter, str);
            painter.drawPixmap(QRect(20, (count * rowHeight+(rowHeight-20)/2), 20, 20),QPixmap(listIcons[count]));
            painter.drawText(QRect(45, count * rowHeight, width()-40, rowHeight), Qt::AlignVCenter, str);

            ++count;
        }
}

void Sidebar::mouseMoveEvent(QMouseEvent *e)
{
    if (e->y() / rowHeight < listItems.count())
        {
            mouseMoveIndex = e->y() / rowHeight;
        }
        else
        {
            mouseMoveIndex = -1;
        }

        update();
}

void Sidebar::mousePressEvent(QMouseEvent *e)
{
    if (e->y() / rowHeight < listItems.count())
        {
            currentIndex = e->y() / rowHeight;
            emit currentItemChanged(currentIndex);
            update();
        }
}

void Sidebar::leaveEvent(QEvent *)
{
    if(mouseMoveIndex !=-1 )
        {
            mouseMoveIndex = -1;
            update();
        }
}
